#!/bin/bash

#set -x

#Script used to configure my bash/zsh environmnents

if [[ -z "$LOCAL_CONFIG_LIB" ]]; then
    LOCAL_SHELL_CONFIG_HOME="$(dirname $0)"
else
    LOCAL_SHELL_CONFIG_HOME="${LOCAL_CONFIG_LIB}/bash"
fi



export LOCAL_SHELL_CONFIG_HOME

export LOCAL_SHELL_PATH_ENV="$HOME/gitworkspace/.dotfiles/bin"

export LOCAL_SHELL_CONFIG_LIB="$LOCAL_SHELL_CONFIG_HOME/lib"
export SYSTEM_SHELL_CONFIG_HOME="$HOME/.shell"
export SYSTEM_SHELL_PATH_ENV="$SYSTEM_SHELL_CONFIG_HOME/bin"
export BASH_RC="$HOME/.bashrc"
export ZSH_RC="$HOME/.zshrc"

__copy_local_bash_config_to_system(){



    if [[ ! -d ${SYSTEM_SHELL_CONFIG_HOME} ]]; then
        mkdir ${SYSTEM_SHELL_CONFIG_HOME}
    fi

    if [[ ! -d ${SYSTEM_SHELL_PATH_ENV} ]]; then
        mkdir ${SYSTEM_SHELL_PATH_ENV}
    fi
    cp $LOCAL_SHELL_PATH_ENV/*  $SYSTEM_SHELL_PATH_ENV

    cp $LOCAL_SHELL_CONFIG_LIB/shell/shell_config  $SYSTEM_SHELL_CONFIG_HOME

    cp $LOCAL_SHELL_CONFIG_LIB/shell/bash_aliases  $SYSTEM_SHELL_CONFIG_HOME

    if [[ ! -f ${SYSTEM_SHELL_CONFIG_HOME}/bash_local  ]] ; then 
        cp ${LOCAL_SHELL_CONFIG_LIB}/shell/bash_local ${SYSTEM_SHELL_CONFIG_HOME}
    fi    

    if [[ ! -f ${SYSTEM_SHELL_CONFIG_HOME}/bash_startup  ]] ; then 
        cp ${LOCAL_SHELL_CONFIG_LIB}/shell/bash_startup ${SYSTEM_SHELL_CONFIG_HOME}
    fi

    if [[ ! -f ${SYSTEM_SHELL_CONFIG_HOME}/local_data  ]] ; then 
        cp ${LOCAL_SHELL_CONFIG_LIB}/shell/local_data ${SYSTEM_SHELL_CONFIG_HOME}
    fi 

    
}

__config_shell_rc(){

    #test if file exists
    if [[ -f $BASH_RC ]] ; then 

        if [[ "$(tail -n 1 $BASH_RC)" =~ .*shell_config$ ]]; then
            echo "configured bashrc"
        else
            echo "source $SYSTEM_SHELL_CONFIG_HOME/shell_config"  >> $BASH_RC
        fi
    fi 

    #test if file exists
    if [[ -f $ZSH_RC ]] ; then 

        if [[ "$(tail -n 1 ${ZSH_RC})" =~ .*shell_config$ ]]; then
            echo "configured zshrc"
        else
            echo "source $SYSTEM_SHELL_CONFIG_HOME/shell_config"  >> $ZSH_RC
        fi
    fi


}

config_shell_env(){
   __copy_local_bash_config_to_system
   __config_shell_rc 
}


config_shell_env




